package com.dwxt.cms.service;

import com.dwxt.cms.dao.PermissionMapper;
import com.dwxt.cms.entity.Permission;
import com.dwxt.cms.entity.PermissionExample;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceAdmin {

    @Autowired
    private PermissionMapper permissionMapper;

    public List<Permission> selectByRoleList(List<Integer> roleIds) {
        return permissionMapper.selectByRoleList(roleIds);
    }

    /**
     * 根据分类查找权限
     *
     * @param categoryList
     * @return
     */
    public List<Permission> selectByCategoryList(List<String> categoryList) {
        PermissionExample example = new PermissionExample();
        example.createCriteria().andCategoryIn(categoryList);
        return permissionMapper.selectByExample(example);
    }

    public List<String> selectDistinctCategoryByRoleId(Integer roleId) {
        return permissionMapper.selectDistinctCategoryByRoleId(roleId);
    }

    public BaseResult createOrUpdatePermission(Permission permission) {
        if(permission.getId()==null){
            permissionMapper.insert(permission);
        }else {
            permissionMapper.updateByPrimaryKeySelective(permission);
        }
        return BaseResult.ok();
    }

    public Permission selectByUrl(String url) {
        PermissionExample example = new PermissionExample();
        example.createCriteria().andUrlEqualTo(url);
        List<Permission> permissions = permissionMapper.selectByExample(example);
        return permissions.isEmpty() ? null : permissions.get(0);
    }

    public int batchDeleteById(Integer[] id) {
        PermissionExample example = new PermissionExample();
        example.createCriteria().andIdIn(Arrays.asList(id));
        return permissionMapper.deleteByExample(example);
    }

    public void update(Permission permission) {
        permissionMapper.updateByPrimaryKeySelective(permission);
    }

    public List<Permission> selectAll() {
        PermissionExample example = new PermissionExample();
        return permissionMapper.selectByExample(example);
    }

    public List<String> selectDistinctCategoryList() {
        return permissionMapper.selectDistinctCategoryList();
    }
}
